package com.qf.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.event.util.EventUtil;
import com.qf.dao.RoomDao;
import com.qf.entity.Room;
import com.qf.entity.RoomPrice;
import com.qf.service.RoomPriceService;
import com.qf.service.RoomService;
import com.qf.util.DateUtil;
import com.qf.util.EventTypeContact;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * (Room)表服务实现类
 *
 * @author makejava
 * @since 2020-09-15 15:55:53
 */
@Service("roomService")
public class RoomServiceImpl extends ServiceImpl<RoomDao, Room> implements RoomService {

    @Autowired
    private RoomPriceService roomPriceService;

    @Autowired
    private EventUtil eventUtil;

    @Override
    @Transactional
    public boolean save(Room room) {

        boolean flag = super.save(room);
        List<RoomPrice> roomPrices = new ArrayList<>();
        room.setRoomPrices(roomPrices);

        //同时生成最近1个月的价格列表
        for (int i = 0; i < 10; i++) {
            RoomPrice roomPrice = new RoomPrice()
                    .setRid(room.getId())
                    .setType(0)//非普通房价
                    .setPrice(room.getPrice())
                    .setNumber(0)
                    .setHasNumber(room.getNumber())
                    .setDate(DateUtil.getNextDate(i));

            roomPrices.add(roomPrice);
        }

        roomPriceService.saveBatch(roomPrices);

        //发布事件 - RabbitMQ
        eventUtil.sendMsg(EventTypeContact.ROOM_PRICE_INSERT, room);

        return flag;
    }

    @Override
    public Room getById(Serializable id) {
        Room room = super.getById(id);
        //查询房间的价格信息
        List<RoomPrice> prices = roomPriceService.list(new QueryWrapper<RoomPrice>().eq("rid", room.getId()));
        return room.setRoomPrices(prices);
    }
}